<?php

class QuestionController extends Controller
{
    public function actionIndex()
    {
        $this->responseJSON("index");
    }

    public function actionError()
    {
        $this->responseJSON("error");
    }

    public function actionCreate()
    {
        $modelQuestion = new Question;
        $question = $_POST;
        $modelQuestion->attributes = $question;
        if($modelQuestion->save()){
            $this->responseJSON($modelQuestion->attributes);
        }else{
            $this->responseJSON("survey error");
        }   
    }

    public function actionRead($id)
    {
        $model = $this->loadModel($id);
        $question = $model->attributes;
        $question['options'] = array();
        foreach ($model->options as $option) {
            $question['options'][] = $option->attributes;
        }
        $this->responseJSON($question);
    }

    public function actionUpdate($id)
    {
        $model = $this->loadModel($id);
        if($_POST){
            $model->attributes = $_POST;
            if($model->save()){
                $this->response($model->attributes);        
            }
            else{
                $this->response("error");           
            }
        }
    }

    public function actionDelete($id)
    {
        if($this->loadModel($id)->delete()){
            $this->responseJSON("success");
        }else{
            $this->responseJSON("false");
        };
    }

    public function loadModel($id)
    {
        $model = Question::model()->findByPk($id);
        if($model===null)
            $this->responseJSON('The requested does not exist.');
        return $model;
    }
}
